"""
2017.06.06
读取文件，使用类保存数据
Class Athlete
"""


class Athlete:
    def __init__(self, a_name, a_dob=None, a_times=[]):
        self.name = a_name
        self.dob = a_dob
        self.times = a_times

    def top3(self):
        # ！！！！不要返回字符串，返回列表可以使得程序更加灵活。
        # return str(sorted(set([sanitize(t) for t in self.times]))[0:3])
        return sorted(set([sanitize(t) for t in self.times]))[0:3]

    def add_time(self, time):
        # 增加元素，使用append
        self.times.append(time)

    def add_times(self, times):
        # 扩展列表使用extend
        self.times.extend(times)


def sanitize(time_string):
    """
    过滤(净化)
    :param time_string:
    :return:
    """
    if '-' in time_string:
        splitter = '-'
    elif ':' in time_string:
        splitter = ':'
    else:
        return time_string
    (mins, secs) = time_string.split(splitter)
    return mins + '.' + secs


# 读取教练的数据
def get_coach_data(filename):
    try:
        with open(filename) as f:
            data = f.readline().strip().split(',')
            a = Athlete(data.pop(0), data.pop(0), data)
        return a
    except IOError as err:
        print('File error: ' + str(err))
        return None


# 将sarah数据文件转为一个列表
sarah = get_coach_data('sarah2.txt')
james = get_coach_data('james2.txt')
mikey = get_coach_data('mikey2.txt')
julie = get_coach_data('julie2.txt')

sarah.add_time('1.11')
sarah.add_times(['1:10', '0-99'])

print(sarah.name + "'s best times are: " + str(sarah.top3()))
print(james.name + "'s best times are: " + str(james.top3()))
print(mikey.name + "'s best times are: " + str(mikey.top3()))
print(julie.name + "'s best times are: " + str(julie.top3()))

# Sarah Sweeney's fastest times are: ['2.18', '2.21', '2.22']
# James Lee's fastest times are: ['2.01', '2.16', '2.22']
# Mikey McManus's fastest times are: ['2.22', '2.31', '2.38']
# Julie Jones's fastest times are: ['2.11', '2.23', '2.59']
